const API_BASE_URL = "https://api.bgm.tv";//开发可以用api.bgm38.tv捏
// const ACCESS_TOKEN = "USpm5paIMoBjdmdk4fyCBHvZ7JFtaKMWmIzkqAxQ"; // 请替换为你的 Access Token

// 封装的 HTTP 请求方法
function request(url, method = "GET", data = {}, headers = {}) {
  return new Promise((resolve, reject) => {
    // 从全局数据或storage中获取accessToken
    const accessToken = getApp().globalData.accessToken || wx.getStorageSync('accessToken');
    
    wx.request({
      url: API_BASE_URL + url,
      method: method,
      data: data,
      header: {
        "Content-Type": "application/json",
        "Authorization": accessToken ? `Bearer ${accessToken}` : '',
        ...headers
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(new Error(`HTTP Error: ${res.statusCode} - ${res.data.message || res.data.error || 'Unknown error'}`));
        }
      },
      fail: (err) => {
        reject(new Error(`Network Error: ${err.message || 'Failed to connect to server'}`));
      }
    });
  });
}

// 获取角色详情
async function getCharacterById(characterId) {
  try {
    const res = await request(`/v0/characters/${characterId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching character detail:", err);
    throw err;
  }
}

// 获取人物详情
async function getPersonById(personId) {
  try {
    const res = await request(`/v0/persons/${personId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching person detail:", err);
    throw err;
  }
}

// 获取每日放送
async function getCalendar() {
  try {
    const res = await request("/calendar", "GET");
    return res;
  } catch (err) {
    console.error("Error fetching calendar:", err);
    throw err;
  }
}

// 检索条目
async function searchSubject(keywords, type = null, responseGroup = "large", start = 0, maxResults = 25) {
  try {
    const params = {
      type: type,
      responseGroup: responseGroup,
      start: start,
      max_results: maxResults,
    };
    const res = await request(`/search/subject/${encodeURIComponent(keywords)}`, "GET", params);
    return res;
  } catch (err) {
    console.error("Error searching subject:", err);
    throw err;
  }
}

//搜索，排行榜和首页都用这个
/*
sort的可用字段值：
      match meilisearch 的默认排序，按照匹配程度
      heat 收藏人数
      rank 排名由高到低
      score 评分

body = {
      keyword,
      sort,
      filter: {
        type: [], //type: 条目类型，参照 SubjectType enum， 或。
        meta_tags: [],//由维基人维护的 tag
        tag: [],//tag: 标签，可以多次出现。且 关系。
        air_date: [],//: 播出日期/发售日期。且 关系。
        rating: [],//用于搜索指定评分的条目。且 关系。
        rank: [],//rank: 用于搜索指定排名的条目。且 关系。
        nsfw: false
      }
    };
*/
async function searchSubjects(limit = 10, offset = 0, body = {}) {
  console.log(offset);
  const res = await request(
    `/v0/search/subjects?limit=${limit}&offset=${offset}`,
    "POST",
    body,       // 请求体
    {},         // 可选 headers
  );
  return res;
}
// 获取用户收藏的条目列表
// 获取用户收藏的条目列表
async function getUserCollections(username, subjectType = null, collectionType = null, limit = 30, offset = 0) {
  try {
    // 构建查询参数对象
    const params = {
      limit: limit,
      offset: offset
    };
    
    // 只有当参数有值时才添加到查询参数中
    if (collectionType !== null && collectionType !== undefined) {
      params.type = collectionType;
    }
    if (subjectType !== null && subjectType !== undefined) {
      params.subject_type = subjectType;
    }
    
    const res = await request(`/v0/users/${username}/collections`, "GET", params);
    return res;
  } catch (err) {
    console.error('Error fetching user collections:', err);
    throw err;
  }
}

// 获取用户对某个条目的收藏信息
async function getUserCollection(username, subjectId) {
  try {
    const res = await request(`/v0/users/${username}/collections/${subjectId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching user collection:", err);
    throw err;
  }
}

// 新增或修改用户对某个条目的收藏
async function postUserCollection(subjectId, payload) {
  try {
    const res = await request(`/v0/users/-/collections/${subjectId}`, "POST", payload);
    return res;
  } catch (err) {
    console.error("Error posting user collection:", err);
    throw err;
  }
}

// 修改用户对某个条目的收藏
async function patchUserCollection(subjectId, payload) {
  try {
    const res = await request(`/v0/users/-/collections/${subjectId}`, "PATCH", payload);
    return res;
  } catch (err) {
    console.error("Error patching user collection:", err);
    throw err;
  }
}

// 获取用户对某个条目的章节收藏信息
async function getUserSubjectEpisodeCollection(subjectId, limit = 100, offset = 0, episodeType = 0) {
  try {
    const params = {
      limit: limit,
      offset: offset,
      episode_type: episodeType
    };
    const res = await request(`/v0/users/-/collections/${subjectId}/episodes`, "GET", params);
    return res;
  } catch (err) {
    console.error("Error fetching user subject episode collection:", err);
    throw err;
  }
}

// 批量更新章节收藏状态
async function patchUserSubjectEpisodeCollection(subjectId, payload) {
  try {
    const res = await request(`/v0/users/-/collections/${subjectId}/episodes`, "PATCH", payload);
    return res;
  } catch (err) {
    console.error("Error patching user subject episode collection:", err);
    throw err;
  }
}

// 获取用户对单个章节的收藏信息
async function getUserEpisodeCollection(episodeId) {
  try {
    const res = await request(`/v0/users/-/collections/-/episodes/${episodeId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching user episode collection:", err);
    throw err;
  }
}

// 更新用户对单个章节的收藏信息
async function putUserEpisodeCollection(episodeId, payload) {
  try {
    const res = await request(`/v0/users/-/collections/-/episodes/${episodeId}`, "PUT", payload);
    return res;
  } catch (err) {
    console.error("Error putting user episode collection:", err);
    throw err;
  }
}


// 获取用户角色收藏列表
async function getUserCharacterCollections(limit = 30, offset = 0) {
  try {
    const username = wx.getStorageSync('username');
    const params = { limit, offset };
    const res = await request(`/v0/users/${username}/collections/-/characters`, "GET", params);
    return res;
  } catch (err) {
    console.error("Error fetching user character collections:", err);
    throw err;
  }
}

// 获取用户单个角色收藏信息
async function getUserCharacterCollection(characterId) {
  try {
    const username = wx.getStorageSync('username');
    const res = await request(`/v0/users/${username}/collections/-/characters/${characterId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching user character collection:", err);
    throw err;
  }
}

// 获取用户人物收藏列表
async function getUserPersonCollections(limit = 30, offset = 0) {
  try {
    const username = wx.getStorageSync('username');
    const params = { limit, offset };
    const res = await request(`/v0/users/${username}/collections/-/persons`, "GET", params);
    return res;
  } catch (err) {
    console.error("Error fetching user person collections:", err);
    throw err;
  }
}

// 获取用户单个人物收藏信息
async function getUserPersonCollection(personId) {
  try {
    const username = wx.getStorageSync('username');
    const res = await request(`/v0/users/${username}/collections/-/persons/${personId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching user person collection:", err);
    throw err;
  }
}

// 获取用户信息
async function getUserInfo(username) {
  try {
    const res = await request(`/v0/users/${username}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching user info:", err);
    throw err;
  }
}

// 获取当前用户信息
async function getMyself() {
  try {
    const res = await request("/v0/me", "GET");
    return res;
  } catch (err) {
    console.error("Error fetching myself info:", err);
    throw err;
  }
}

// 获取用户头像
async function getUserAvatar(username, type = "medium") {
  try {
    const res = await request(`/v0/users/${username}/avatar`, "GET", { type });
    return res;
  } catch (err) {
    console.error("Error fetching user avatar:", err);
    throw err;
  }
}

// 获取排行榜
async function getRanking(subjectType = null, limit = 25, offset = 0) {
  try {
    const params = { type: subjectType, limit, offset };
    const res = await request("/v0/subjects", "GET", params);
    return res;
  } catch (err) {
    console.error("Error fetching ranking:", err);
    throw err;
  }
}

// 获取条目
async function getSubjectById(subjectId) {
  try {
    const res = await request(`/v0/subjects/${subjectId}`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching user info:", err);
    throw err;
  }
}

// 获取条目相关的人员信息
async function getSubjectPersons(subjectId) {
  try {
    const res = await request(`/v0/subjects/${subjectId}/persons`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching subject persons:", err);
    throw err;
  }
}

// 获取条目相关的人物角色信息
async function getSubjectCharacters(subjectId) {
  try {
    const res = await request(`/v0/subjects/${subjectId}/characters`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching subject characters:", err);
    throw err;
  }
}

// 获取与该条目相关联的其他条目信息（比如同系列作品）
async function getSubjectRelations(subjectId) {
  try {
    const res = await request(`/v0/subjects/${subjectId}/subjects`, "GET");
    return res;
  } catch (err) {
    console.error("Error fetching subject relations:", err);
    throw err;
  }
}

// 获取章节列表信息
async function getEpisodes(subjectId = null, type = 0, limit = 100, offset = 0) {
  try {
    const params = {
      subject_id: subjectId,
      type: type,
      limit: limit,
      offset: offset
    };
    const res = await request("/v0/episodes", "GET", params);
    return res;
  } catch (err) {
    console.error("Error fetching episodes:", err);
    throw err;
  }
}

async function getTimetable() {
  try {
    const res = await request("/calendar", "GET");
    // 接口返回的是对象数组，转换为二维数组
    if (Array.isArray(res)) {
      // 转换为按星期索引的二维数组 [周一数据, 周二数据, ...]
      const weekData = Array(7).fill().map(() => []);
      res.forEach(day => {
        // weekday.id: 0=周日, 1=周一, ...6=周六
        const weekdayIndex = day.weekday.id;
        // 转换为新索引：周一=0，周日=6
        const ourIndex = weekdayIndex === 0 ? 6 : weekdayIndex - 1;
        if (ourIndex >= 0 && ourIndex < 7 && Array.isArray(day.items)) {
          weekData[ourIndex] = day.items;
        }
      });
      return { data: weekData };
    }
    return { data: [] };
  } catch (err) {
    console.error("获取时间表失败", err);
    return { data: Array(7).fill([]) };
  }
}

// 将 request.js 放入微信小程序的 utils 文件夹中，然后在其他页面中通过 require 或 import 引入

module.exports = {
  getCalendar,
  searchSubject,
  searchSubjects,
  getUserCollections,
  getUserCollection,
  postUserCollection,
  patchUserCollection,
  getUserSubjectEpisodeCollection,
  patchUserSubjectEpisodeCollection,
  getUserEpisodeCollection,
  putUserEpisodeCollection,
  getUserCharacterCollections,
  getUserCharacterCollection,
  getUserPersonCollections,
  getUserPersonCollection,
  getUserInfo,
  getMyself,
  getUserAvatar,
  getRanking,
  getSubjectById,
  getSubjectPersons,
  getSubjectCharacters,
  getSubjectRelations,
  getEpisodes,
  getTimetable,
  getCharacterById,
  getPersonById
};